package com.uniflow.controller;

import com.uniflow.common.PageResult;
import com.uniflow.common.Result;
import com.uniflow.entity.TaskCenter;
import com.uniflow.entity.User;
import com.uniflow.service.TaskCenterService;
import com.uniflow.service.UserService;
import com.uniflow.service.WorkflowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 任务中心控制器
 */
@Api(tags = "任务管理")
@RestController
@RequestMapping("/api/v1/tasks")
public class TaskCenterController {
    
    @Autowired
    private TaskCenterService taskCenterService;
    
    @Autowired
    private WorkflowService workflowService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 分页查询任务列表
     */
    @ApiOperation("分页查询任务列表")
    @GetMapping("/list")
    public Result<PageResult<TaskCenter>> getTaskList(
            @ApiParam("页码") @RequestParam(defaultValue = "1") int pageNum,
            @ApiParam("页大小") @RequestParam(defaultValue = "10") int pageSize,
            @ApiParam("任务标题") @RequestParam(required = false) String title,
            @ApiParam("任务类型") @RequestParam(required = false) String type,
            @ApiParam("任务分类") @RequestParam(required = false) String category,
            @ApiParam("任务状态") @RequestParam(required = false) String status,
            @ApiParam("优先级") @RequestParam(required = false) Integer priority,
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId,
            @ApiParam("创建人ID") @RequestParam(required = false) String createdBy,
            @ApiParam("业务类型") @RequestParam(required = false) String businessType,
            @ApiParam("流程实例ID") @RequestParam(required = false) String processInstanceId,
            @ApiParam("表单ID") @RequestParam(required = false) String formId,
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate,
            @ApiParam("是否过期") @RequestParam(required = false) Boolean overdue,
            @ApiParam("标签") @RequestParam(required = false) String tags) {
        
        PageResult<TaskCenter> result = taskCenterService.getTaskList(pageNum, pageSize, title, 
                type, category, status, priority, assigneeId, createdBy, businessType, 
                processInstanceId, formId, startDate, endDate, overdue, tags);
        
        return Result.success(result);
    }
    
    /**
     * 根据ID查询任务详情
     */
    @ApiOperation("根据ID查询任务详情")
    @GetMapping("/{id}")
    public Result<TaskCenter> getTaskById(@ApiParam("任务ID") @PathVariable String id) {
        TaskCenter task = taskCenterService.getTaskById(id);
        if (task == null) {
            return Result.error("任务不存在");
        }
        return Result.success(task);
    }
    
    /**
     * 根据执行人查询任务列表
     */
    @ApiOperation("根据执行人查询任务列表")
    @GetMapping("/assignee/{assigneeId}")
    public Result<List<TaskCenter>> getTasksByAssigneeId(
            @ApiParam("执行人ID") @PathVariable String assigneeId,
            @ApiParam("任务状态") @RequestParam(required = false) String status) {
        
        List<TaskCenter> tasks = taskCenterService.getTasksByAssigneeId(assigneeId, status);
        return Result.success(tasks);
    }
    
    /**
     * 根据创建人查询任务列表
     */
    @ApiOperation("根据创建人查询任务列表")
    @GetMapping("/creator/{createdBy}")
    public Result<List<TaskCenter>> getTasksByCreatedBy(
            @ApiParam("创建人ID") @PathVariable String createdBy,
            @ApiParam("任务状态") @RequestParam(required = false) String status) {
        
        List<TaskCenter> tasks = taskCenterService.getTasksByCreatedBy(createdBy, status);
        return Result.success(tasks);
    }
    
    /**
     * 根据业务键查询任务
     */
    @ApiOperation("根据业务键查询任务")
    @GetMapping("/business-key/{businessKey}")
    public Result<TaskCenter> getTaskByBusinessKey(@ApiParam("业务键") @PathVariable String businessKey) {
        TaskCenter task = taskCenterService.getTaskByBusinessKey(businessKey);
        return Result.success(task);
    }
    
    /**
     * 根据流程实例ID查询任务列表
     */
    @ApiOperation("根据流程实例ID查询任务列表")
    @GetMapping("/process-instance/{processInstanceId}")
    public Result<List<TaskCenter>> getTasksByProcessInstanceId(
            @ApiParam("流程实例ID") @PathVariable String processInstanceId) {
        
        List<TaskCenter> tasks = taskCenterService.getTasksByProcessInstanceId(processInstanceId);
        return Result.success(tasks);
    }
    
    /**
     * 根据流程任务ID查询任务
     */
    @ApiOperation("根据流程任务ID查询任务")
    @GetMapping("/process-task/{processTaskId}")
    public Result<TaskCenter> getTaskByProcessTaskId(@ApiParam("流程任务ID") @PathVariable String processTaskId) {
        TaskCenter task = taskCenterService.getTaskByProcessTaskId(processTaskId);
        return Result.success(task);
    }
    
    /**
     * 根据表单ID查询任务列表
     */
    @ApiOperation("根据表单ID查询任务列表")
    @GetMapping("/form/{formId}")
    public Result<List<TaskCenter>> getTasksByFormId(@ApiParam("表单ID") @PathVariable String formId) {
        List<TaskCenter> tasks = taskCenterService.getTasksByFormId(formId);
        return Result.success(tasks);
    }
    
    /**
     * 根据表单数据ID查询任务
     */
    @ApiOperation("根据表单数据ID查询任务")
    @GetMapping("/form-data/{formDataId}")
    public Result<TaskCenter> getTaskByFormDataId(@ApiParam("表单数据ID") @PathVariable String formDataId) {
        TaskCenter task = taskCenterService.getTaskByFormDataId(formDataId);
        return Result.success(task);
    }
    
    /**
     * 查询我的任务列表
     */
    @ApiOperation("查询我的任务列表")
    @GetMapping("/my-tasks")
    public Result<PageResult<TaskCenter>> getMyTasks(
            @ApiParam("页码") @RequestParam(defaultValue = "1") int pageNum,
            @ApiParam("页大小") @RequestParam(defaultValue = "10") int pageSize,
            @ApiParam("用户ID") @RequestParam String userId,
            @ApiParam("任务状态") @RequestParam(required = false) String status,
            @ApiParam("任务类型") @RequestParam(required = false) String type,
            @ApiParam("优先级") @RequestParam(required = false) Integer priority,
            @ApiParam("是否过期") @RequestParam(required = false) Boolean overdue) {
        
        PageResult<TaskCenter> result = taskCenterService.getMyTasks(pageNum, pageSize, userId, 
                status, type, priority, overdue);
        
        return Result.success(result);
    }
    
    /**
     * 查询我创建的任务列表
     */
    @ApiOperation("查询我创建的任务列表")
    @GetMapping("/my-created-tasks")
    public Result<PageResult<TaskCenter>> getMyCreatedTasks(
            @ApiParam("页码") @RequestParam(defaultValue = "1") int pageNum,
            @ApiParam("页大小") @RequestParam(defaultValue = "10") int pageSize,
            @ApiParam("用户ID") @RequestParam String userId,
            @ApiParam("任务状态") @RequestParam(required = false) String status,
            @ApiParam("任务类型") @RequestParam(required = false) String type) {
        
        PageResult<TaskCenter> result = taskCenterService.getMyCreatedTasks(pageNum, pageSize, 
                userId, status, type);
        
        return Result.success(result);
    }
    
    /**
     * 查询候选任务列表（可认领的任务）
     */
    @ApiOperation("查询候选任务列表")
    @GetMapping("/candidate-tasks")
    public Result<PageResult<TaskCenter>> getCandidateTasks(
            @ApiParam("页码") @RequestParam(defaultValue = "1") int pageNum,
            @ApiParam("页大小") @RequestParam(defaultValue = "10") int pageSize,
            @ApiParam("用户ID") @RequestParam String userId,
            @ApiParam("用户组列表") @RequestParam(required = false) List<String> userGroups,
            @ApiParam("任务类型") @RequestParam(required = false) String type,
            @ApiParam("优先级") @RequestParam(required = false) Integer priority) {
        
        // 如果没有提供用户组，则从用户角色中获取
        List<String> finalUserGroups = userGroups;
        if (finalUserGroups == null || finalUserGroups.isEmpty()) {
            try {
                User user = userService.getUserWithRoles(userId);
                if (user != null && user.getRoles() != null) {
                    finalUserGroups = user.getRoles().stream()
                            .map(role -> role.getName())
                            .collect(java.util.stream.Collectors.toList());
                }
            } catch (Exception e) {
                // 如果获取用户角色失败，继续使用空列表
                finalUserGroups = new java.util.ArrayList<>();
            }
        }
        
        PageResult<TaskCenter> result = taskCenterService.getCandidateTasks(pageNum, pageSize, 
                userId, finalUserGroups, type, priority);
        
        return Result.success(result);
    }
    
    /**
     * 查询过期任务列表
     */
    @ApiOperation("查询过期任务列表")
    @GetMapping("/overdue-tasks")
    public Result<PageResult<TaskCenter>> getOverdueTasks(
            @ApiParam("页码") @RequestParam(defaultValue = "1") int pageNum,
            @ApiParam("页大小") @RequestParam(defaultValue = "10") int pageSize,
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId,
            @ApiParam("任务类型") @RequestParam(required = false) String type) {
        
        PageResult<TaskCenter> result = taskCenterService.getOverdueTasks(pageNum, pageSize, 
                assigneeId, type);
        
        return Result.success(result);
    }
    
    /**
     * 查询即将到期的任务列表
     */
    @ApiOperation("查询即将到期的任务列表")
    @GetMapping("/upcoming-tasks")
    public Result<PageResult<TaskCenter>> getUpcomingTasks(
            @ApiParam("页码") @RequestParam(defaultValue = "1") int pageNum,
            @ApiParam("页大小") @RequestParam(defaultValue = "10") int pageSize,
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId,
            @ApiParam("小时数") @RequestParam(defaultValue = "24") Integer hours) {
        
        PageResult<TaskCenter> result = taskCenterService.getUpcomingTasks(pageNum, pageSize, 
                assigneeId, hours);
        
        return Result.success(result);
    }
    
    /**
     * 创建任务
     */
    @ApiOperation("创建任务")
    @PostMapping
    public Result<TaskCenter> createTask(@RequestBody TaskCreateRequest request, HttpServletRequest httpRequest) {
        // 从请求中获取当前用户信息（实际项目中应该从JWT或Session中获取）
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        TaskCenter task = new TaskCenter();
        task.setTitle(request.getTitle());
        task.setDescription(request.getDescription());
        task.setType(request.getType());
        task.setCategory(request.getCategory());
        task.setPriority(request.getPriority());
        task.setAssigneeId(request.getAssigneeId());
        task.setAssigneeName(request.getAssigneeName());
        task.setBusinessKey(request.getBusinessKey());
        task.setBusinessType(request.getBusinessType());
        task.setBusinessData(request.getBusinessData());
        task.setProcessInstanceId(request.getProcessInstanceId());
        task.setProcessDefinitionId(request.getProcessDefinitionId());
        task.setProcessDefinitionKey(request.getProcessDefinitionKey());
        task.setProcessTaskId(request.getProcessTaskId());
        task.setFormId(request.getFormId());
        task.setFormDataId(request.getFormDataId());
        task.setStartTime(request.getStartTime());
        task.setDueTime(request.getDueTime());
        task.setTagList(request.getTags());
        task.setRemark(request.getRemark());
        task.setExtend(request.getExtend());
        task.setCreatedBy(currentUserId);
        task.setCreatedByName(currentUserName);
        task.setCreatedAt(LocalDateTime.now());
        
        TaskCenter createdTask = taskCenterService.createTask(task);
        return Result.success(createdTask);
    }
    
    /**
     * 更新任务
     */
    @ApiOperation("更新任务")
    @PutMapping("/{id}")
    public Result<TaskCenter> updateTask(@ApiParam("任务ID") @PathVariable String id, 
                                        @RequestBody TaskUpdateRequest request, 
                                        HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        TaskCenter task = new TaskCenter();
        task.setId(id);
        task.setTitle(request.getTitle());
        task.setDescription(request.getDescription());
        task.setType(request.getType());
        task.setCategory(request.getCategory());
        task.setPriority(request.getPriority());
        task.setAssigneeId(request.getAssigneeId());
        task.setAssigneeName(request.getAssigneeName());
        task.setBusinessData(request.getBusinessData());
        task.setDueTime(request.getDueTime());
        task.setTagList(request.getTags());
        task.setRemark(request.getRemark());
        task.setExtend(request.getExtend());
        task.setUpdatedBy(currentUserId);
        task.setUpdatedByName(currentUserName);
        task.setUpdatedAt(LocalDateTime.now());
        
        TaskCenter updatedTask = taskCenterService.updateTask(task);
        return Result.success(updatedTask);
    }
    
    /**
     * 删除任务
     */
    @ApiOperation("删除任务")
    @DeleteMapping("/{id}")
    public Result<Void> deleteTask(@ApiParam("任务ID") @PathVariable String id) {
        taskCenterService.deleteTask(id);
        return Result.success();
    }
    
    /**
     * 批量删除任务
     */
    @ApiOperation("批量删除任务")
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteTasks(@RequestBody List<String> ids) {
        taskCenterService.batchDeleteTasks(ids);
        return Result.success();
    }
    
    /**
     * 分配任务
     */
    @ApiOperation("分配任务")
    @PostMapping("/{id}/assign")
    public Result<Void> assignTask(@ApiParam("任务ID") @PathVariable String id, 
                                  @RequestBody TaskAssignRequest request, 
                                  HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        taskCenterService.assignTask(id, request.getAssigneeId(), request.getAssigneeName(), 
                currentUserId, currentUserName);
        
        return Result.success();
    }
    
    /**
     * 批量分配任务
     */
    @ApiOperation("批量分配任务")
    @PostMapping("/batch-assign")
    public Result<Void> batchAssignTask(@RequestBody TaskBatchAssignRequest request, 
                                       HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        taskCenterService.batchAssignTask(request.getIds(), request.getAssigneeId(), 
                request.getAssigneeName(), currentUserId, currentUserName);
        
        return Result.success();
    }
    
    /**
     * 认领任务
     */
    @ApiOperation("认领任务")
    @PostMapping("/{id}/claim")
    public Result<Void> claimTask(@ApiParam("任务ID") @PathVariable String id, 
                                 HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        taskCenterService.claimTask(id, currentUserId, currentUserName);
        return Result.success();
    }
    
    /**
     * 开始任务
     */
    @ApiOperation("开始任务")
    @PostMapping("/{id}/start")
    public Result<Void> startTask(@ApiParam("任务ID") @PathVariable String id, 
                                 HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        taskCenterService.startTask(id, currentUserId, currentUserName);
        return Result.success();
    }
    
    /**
     * 暂停任务
     */
    @ApiOperation("暂停任务")
    @PostMapping("/{id}/suspend")
    public Result<Void> suspendTask(@ApiParam("任务ID") @PathVariable String id, 
                                   HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        taskCenterService.suspendTask(id, currentUserId, currentUserName);
        return Result.success();
    }
    
    /**
     * 恢复任务
     */
    @ApiOperation("恢复任务")
    @PostMapping("/{id}/resume")
    public Result<Void> resumeTask(@ApiParam("任务ID") @PathVariable String id, 
                                  HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        taskCenterService.resumeTask(id, currentUserId, currentUserName);
        return Result.success();
    }
    
    /**
     * 完成任务
     */
    @ApiOperation("完成任务")
    @PostMapping("/{id}/complete")
    public Result<Void> completeTask(@ApiParam("任务ID") @PathVariable String id, 
                                    HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        taskCenterService.completeTask(id, currentUserId, currentUserName);
        return Result.success();
    }
    
    /**
     * 审批任务（同意）
     */
    @ApiOperation("审批任务")
    @PostMapping("/{id}/approve")
    public Result<Void> approveTask(@ApiParam("任务ID") @PathVariable String id,
                                   @RequestBody(required = false) TaskApprovalRequest request,
                                   HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        if (!StringUtils.hasText(currentUserId)) {
            return Result.error("用户未登录");
        }
        
        try {
            String comment = request != null ? request.getComment() : null;
            Map<String, Object> variables = request != null ? request.getVariables() : null;
            
            // 如果任务有对应的Flowable任务，使用WorkflowService
            TaskCenter task = taskCenterService.getTaskById(id);
            if (task != null && StringUtils.hasText(task.getProcessTaskId())) {
                workflowService.approveTask(task.getProcessTaskId(), comment, variables);
            }
            
            // 更新任务中心的任务状态
            taskCenterService.completeTask(id, currentUserId, httpRequest.getHeader("X-User-Name"));
            return Result.success();
        } catch (Exception e) {
            return Result.error("审批任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 拒绝任务（驳回）
     */
    @ApiOperation("拒绝任务")
    @PostMapping("/{id}/reject")
    public Result<Void> rejectTask(@ApiParam("任务ID") @PathVariable String id,
                                  @RequestBody TaskRejectRequest request,
                                  HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        if (!StringUtils.hasText(currentUserId)) {
            return Result.error("用户未登录");
        }
        
        try {
            // 如果任务有对应的Flowable任务，使用WorkflowService
            TaskCenter task = taskCenterService.getTaskById(id);
            if (task != null && StringUtils.hasText(task.getProcessTaskId())) {
                workflowService.rejectTask(task.getProcessTaskId(), request.getReason(), request.getVariables());
            }
            
            // 更新任务中心的任务状态为已拒绝
            taskCenterService.updateTaskStatus(id, "rejected", currentUserId, httpRequest.getHeader("X-User-Name"));
            return Result.success();
        } catch (Exception e) {
            return Result.error("拒绝任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 转办任务
     */
    @ApiOperation("转办任务")
    @PostMapping("/{id}/transfer")
    public Result<Void> transferTask(@ApiParam("任务ID") @PathVariable String id,
                                    @RequestBody TaskTransferRequest request,
                                    HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        if (!StringUtils.hasText(currentUserId)) {
            return Result.error("用户未登录");
        }
        
        try {
            // 如果任务有对应的Flowable任务，使用WorkflowService
            TaskCenter task = taskCenterService.getTaskById(id);
            if (task != null && StringUtils.hasText(task.getProcessTaskId())) {
                workflowService.transferTask(task.getProcessTaskId(), request.getTargetUserId(), request.getReason());
            }
            
            // 更新任务中心的任务分配
            taskCenterService.assignTask(id, request.getTargetUserId(), request.getTargetUserName(), 
                    currentUserId, httpRequest.getHeader("X-User-Name"));
            return Result.success();
        } catch (Exception e) {
            return Result.error("转办任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 取消任务
     */
    @ApiOperation("取消任务")
    @PostMapping("/{id}/cancel")
    public Result<Void> cancelTask(@ApiParam("任务ID") @PathVariable String id, 
                                  HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        taskCenterService.cancelTask(id, currentUserId, currentUserName);
        return Result.success();
    }
    
    /**
     * 更新任务状态
     */
    @ApiOperation("更新任务状态")
    @PutMapping("/{id}/status")
    public Result<Void> updateTaskStatus(@ApiParam("任务ID") @PathVariable String id, 
                                        @RequestBody TaskStatusUpdateRequest request, 
                                        HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        taskCenterService.updateTaskStatus(id, request.getStatus(), currentUserId, currentUserName);
        return Result.success();
    }
    
    /**
     * 批量更新任务状态
     */
    @ApiOperation("批量更新任务状态")
    @PutMapping("/batch-status")
    public Result<Void> batchUpdateTaskStatus(@RequestBody TaskBatchStatusUpdateRequest request, 
                                             HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        taskCenterService.batchUpdateTaskStatus(request.getIds(), request.getStatus(), 
                currentUserId, currentUserName);
        
        return Result.success();
    }
    
    /**
     * 更新任务优先级
     */
    @ApiOperation("更新任务优先级")
    @PutMapping("/{id}/priority")
    public Result<Void> updateTaskPriority(@ApiParam("任务ID") @PathVariable String id, 
                                          @RequestBody TaskPriorityUpdateRequest request, 
                                          HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        taskCenterService.updateTaskPriority(id, request.getPriority(), currentUserId, currentUserName);
        return Result.success();
    }
    
    /**
     * 批量更新任务优先级
     */
    @ApiOperation("批量更新任务优先级")
    @PutMapping("/batch-priority")
    public Result<Void> batchUpdateTaskPriority(@RequestBody TaskBatchPriorityUpdateRequest request, 
                                               HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        taskCenterService.batchUpdateTaskPriority(request.getIds(), request.getPriority(), 
                currentUserId, currentUserName);
        
        return Result.success();
    }
    
    /**
     * 更新任务到期时间
     */
    @ApiOperation("更新任务到期时间")
    @PutMapping("/{id}/due-time")
    public Result<Void> updateTaskDueTime(@ApiParam("任务ID") @PathVariable String id, 
                                         @RequestBody TaskDueTimeUpdateRequest request, 
                                         HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        taskCenterService.updateTaskDueTime(id, request.getDueTime(), currentUserId, currentUserName);
        return Result.success();
    }
    
    /**
     * 批量更新任务到期时间
     */
    @ApiOperation("批量更新任务到期时间")
    @PutMapping("/batch-due-time")
    public Result<Void> batchUpdateTaskDueTime(@RequestBody TaskBatchDueTimeUpdateRequest request, 
                                              HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        taskCenterService.batchUpdateTaskDueTime(request.getIds(), request.getDueTime(), 
                currentUserId, currentUserName);
        
        return Result.success();
    }
    
    /**
     * 更新任务标签
     */
    @ApiOperation("更新任务标签")
    @PutMapping("/{id}/tags")
    public Result<Void> updateTaskTags(@ApiParam("任务ID") @PathVariable String id, 
                                      @RequestBody TaskTagsUpdateRequest request, 
                                      HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        taskCenterService.updateTaskTags(id, request.getTags(), currentUserId, currentUserName);
        return Result.success();
    }
    
    /**
     * 批量更新任务标签
     */
    @ApiOperation("批量更新任务标签")
    @PutMapping("/batch-tags")
    public Result<Void> batchUpdateTaskTags(@RequestBody TaskBatchTagsUpdateRequest request, 
                                           HttpServletRequest httpRequest) {
        
        String currentUserId = httpRequest.getHeader("X-User-Id");
        String currentUserName = httpRequest.getHeader("X-User-Name");
        
        taskCenterService.batchUpdateTaskTags(request.getIds(), request.getTags(), 
                currentUserId, currentUserName);
        
        return Result.success();
    }
    
    /**
     * 批量更新任务排序
     */
    @ApiOperation("批量更新任务排序")
    @PutMapping("/batch-sort")
    public Result<Void> batchUpdateTaskSort(@RequestBody List<Map<String, Object>> taskSorts) {
        taskCenterService.batchUpdateTaskSort(taskSorts);
        return Result.success();
    }
    
    /**
     * 检查业务键是否存在
     */
    @ApiOperation("检查业务键是否存在")
    @GetMapping("/check-business-key")
    public Result<Boolean> checkBusinessKeyExists(
            @ApiParam("业务键") @RequestParam String businessKey,
            @ApiParam("排除的任务ID") @RequestParam(required = false) String excludeId) {
        
        boolean exists = taskCenterService.isBusinessKeyExists(businessKey, excludeId);
        return Result.success(exists);
    }
    
    /**
     * 获取任务统计信息
     */
    @ApiOperation("获取任务统计信息")
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getTaskStatistics(
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId) {
        
        Map<String, Object> statistics = taskCenterService.getTaskStatistics(assigneeId);
        return Result.success(statistics);
    }
    
    /**
     * 根据状态统计任务数量
     */
    @ApiOperation("根据状态统计任务数量")
    @GetMapping("/statistics/status")
    public Result<List<Map<String, Object>>> getTaskCountByStatus(
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId) {
        
        List<Map<String, Object>> statistics = taskCenterService.getTaskCountByStatus(assigneeId);
        return Result.success(statistics);
    }
    
    /**
     * 根据类型统计任务数量
     */
    @ApiOperation("根据类型统计任务数量")
    @GetMapping("/statistics/type")
    public Result<List<Map<String, Object>>> getTaskCountByType(
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId,
            @ApiParam("限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        
        List<Map<String, Object>> statistics = taskCenterService.getTaskCountByType(assigneeId, limit);
        return Result.success(statistics);
    }
    
    /**
     * 根据分类统计任务数量
     */
    @ApiOperation("根据分类统计任务数量")
    @GetMapping("/statistics/category")
    public Result<List<Map<String, Object>>> getTaskCountByCategory(
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId,
            @ApiParam("限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        
        List<Map<String, Object>> statistics = taskCenterService.getTaskCountByCategory(assigneeId, limit);
        return Result.success(statistics);
    }
    
    /**
     * 根据优先级统计任务数量
     */
    @ApiOperation("根据优先级统计任务数量")
    @GetMapping("/statistics/priority")
    public Result<List<Map<String, Object>>> getTaskCountByPriority(
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId) {
        
        List<Map<String, Object>> statistics = taskCenterService.getTaskCountByPriority(assigneeId);
        return Result.success(statistics);
    }
    
    /**
     * 根据创建人统计任务数量
     */
    @ApiOperation("根据创建人统计任务数量")
    @GetMapping("/statistics/creator")
    public Result<List<Map<String, Object>>> getTaskCountByCreator(
            @ApiParam("限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        
        List<Map<String, Object>> statistics = taskCenterService.getTaskCountByCreator(limit);
        return Result.success(statistics);
    }
    
    /**
     * 根据执行人统计任务数量
     */
    @ApiOperation("根据执行人统计任务数量")
    @GetMapping("/statistics/assignee")
    public Result<List<Map<String, Object>>> getTaskCountByAssignee(
            @ApiParam("限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        
        List<Map<String, Object>> statistics = taskCenterService.getTaskCountByAssignee(limit);
        return Result.success(statistics);
    }
    
    /**
     * 根据时间统计任务数量
     */
    @ApiOperation("根据时间统计任务数量")
    @GetMapping("/statistics/date")
    public Result<List<Map<String, Object>>> getTaskCountByDate(
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId,
            @ApiParam("开始时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        
        List<Map<String, Object>> statistics = taskCenterService.getTaskCountByDate(assigneeId, startDate, endDate);
        return Result.success(statistics);
    }
    
    /**
     * 根据时间统计任务数量（按月）
     */
    @ApiOperation("根据时间统计任务数量（按月）")
    @GetMapping("/statistics/month")
    public Result<List<Map<String, Object>>> getTaskCountByMonth(
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId,
            @ApiParam("开始时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        
        List<Map<String, Object>> statistics = taskCenterService.getTaskCountByMonth(assigneeId, startDate, endDate);
        return Result.success(statistics);
    }
    
    /**
     * 获取任务完成率统计
     */
    @ApiOperation("获取任务完成率统计")
    @GetMapping("/statistics/completion-rate")
    public Result<Map<String, Object>> getTaskCompletionRate(
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId,
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        
        Map<String, Object> statistics = taskCenterService.getTaskCompletionRate(assigneeId, startDate, endDate);
        return Result.success(statistics);
    }
    
    /**
     * 获取任务平均处理时间
     */
    @ApiOperation("获取任务平均处理时间")
    @GetMapping("/statistics/average-processing-time")
    public Result<Map<String, Object>> getTaskAverageProcessingTime(
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId,
            @ApiParam("任务类型") @RequestParam(required = false) String type,
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        
        Map<String, Object> statistics = taskCenterService.getTaskAverageProcessingTime(assigneeId, type, startDate, endDate);
        return Result.success(statistics);
    }
    
    /**
     * 获取过期任务统计
     */
    @ApiOperation("获取过期任务统计")
    @GetMapping("/statistics/overdue")
    public Result<Map<String, Object>> getOverdueTaskStatistics(
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId) {
        
        Map<String, Object> statistics = taskCenterService.getOverdueTaskStatistics(assigneeId);
        return Result.success(statistics);
    }
    
    /**
     * 获取待处理任务数量
     */
    @ApiOperation("获取待处理任务数量")
    @GetMapping("/statistics/pending-count")
    public Result<Integer> getPendingTaskCount(
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId) {
        
        int count = taskCenterService.getPendingTaskCount(assigneeId);
        return Result.success(count);
    }
    
    /**
     * 获取今日新增任务数量
     */
    @ApiOperation("获取今日新增任务数量")
    @GetMapping("/statistics/today-new-count")
    public Result<Integer> getTodayNewTaskCount(
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId) {
        
        int count = taskCenterService.getTodayNewTaskCount(assigneeId);
        return Result.success(count);
    }
    
    /**
     * 获取今日完成任务数量
     */
    @ApiOperation("获取今日完成任务数量")
    @GetMapping("/statistics/today-completed-count")
    public Result<Integer> getTodayCompletedTaskCount(
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId) {
        
        int count = taskCenterService.getTodayCompletedTaskCount(assigneeId);
        return Result.success(count);
    }
    
    /**
     * 获取本周任务统计
     */
    @ApiOperation("获取本周任务统计")
    @GetMapping("/statistics/weekly")
    public Result<Map<String, Object>> getWeeklyTaskStatistics(
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId) {
        
        Map<String, Object> statistics = taskCenterService.getWeeklyTaskStatistics(assigneeId);
        return Result.success(statistics);
    }
    
    /**
     * 获取本月任务统计
     */
    @ApiOperation("获取本月任务统计")
    @GetMapping("/statistics/monthly")
    public Result<Map<String, Object>> getMonthlyTaskStatistics(
            @ApiParam("执行人ID") @RequestParam(required = false) String assigneeId) {
        
        Map<String, Object> statistics = taskCenterService.getMonthlyTaskStatistics(assigneeId);
        return Result.success(statistics);
    }
    
    /**
     * 查询任务分类列表
     */
    @ApiOperation("查询任务分类列表")
    @GetMapping("/categories")
    public Result<List<String>> getTaskCategories() {
        List<String> categories = taskCenterService.getTaskCategories();
        return Result.success(categories);
    }
    
    /**
     * 查询任务类型列表
     */
    @ApiOperation("查询任务类型列表")
    @GetMapping("/types")
    public Result<List<String>> getTaskTypes() {
        List<String> types = taskCenterService.getTaskTypes();
        return Result.success(types);
    }
    
    /**
     * 查询任务标签列表
     */
    @ApiOperation("查询任务标签列表")
    @GetMapping("/tags")
    public Result<List<String>> getTaskTags(
            @ApiParam("限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        
        List<String> tags = taskCenterService.getTaskTags(limit);
        return Result.success(tags);
    }
    
    /**
     * 查询相关任务列表
     */
    @ApiOperation("查询相关任务列表")
    @GetMapping("/related")
    public Result<List<TaskCenter>> getRelatedTasks(
            @ApiParam("业务键") @RequestParam String businessKey,
            @ApiParam("业务类型") @RequestParam(required = false) String businessType,
            @ApiParam("排除的任务ID") @RequestParam(required = false) String excludeId) {
        
        List<TaskCenter> tasks = taskCenterService.getRelatedTasks(businessKey, businessType, excludeId);
        return Result.success(tasks);
    }
    
    /**
     * 查询任务依赖关系
     */
    @ApiOperation("查询任务依赖关系")
    @GetMapping("/{id}/dependencies")
    public Result<List<Map<String, Object>>> getTaskDependencies(@ApiParam("任务ID") @PathVariable String id) {
        List<Map<String, Object>> dependencies = taskCenterService.getTaskDependencies(id);
        return Result.success(dependencies);
    }
    
    /**
     * 查询子任务列表
     */
    @ApiOperation("查询子任务列表")
    @GetMapping("/{id}/sub-tasks")
    public Result<List<TaskCenter>> getSubTasks(@ApiParam("父任务ID") @PathVariable String id) {
        List<TaskCenter> subTasks = taskCenterService.getSubTasks(id);
        return Result.success(subTasks);
    }
    
    /**
     * 查询父任务
     */
    @ApiOperation("查询父任务")
    @GetMapping("/{id}/parent-task")
    public Result<TaskCenter> getParentTask(@ApiParam("任务ID") @PathVariable String id) {
        TaskCenter parentTask = taskCenterService.getParentTask(id);
        return Result.success(parentTask);
    }
    
    // 请求数据结构定义
    
    public static class TaskCreateRequest {
        private String title;
        private String description;
        private String type;
        private String category;
        private Integer priority;
        private String assigneeId;
        private String assigneeName;
        private String businessKey;
        private String businessType;
        private Map<String, Object> businessData;
        private String processInstanceId;
        private String processDefinitionId;
        private String processDefinitionKey;
        private String processTaskId;
        private String formId;
        private String formDataId;
        private LocalDateTime startTime;
        private LocalDateTime dueTime;
        private List<String> tags;
        private String remark;
        private Map<String, Object> extend;
        
        // Getters and Setters
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        public String getType() { return type; }
        public void setType(String type) { this.type = type; }
        public String getCategory() { return category; }
        public void setCategory(String category) { this.category = category; }
        public Integer getPriority() { return priority; }
        public void setPriority(Integer priority) { this.priority = priority; }
        public String getAssigneeId() { return assigneeId; }
        public void setAssigneeId(String assigneeId) { this.assigneeId = assigneeId; }
        public String getAssigneeName() { return assigneeName; }
        public void setAssigneeName(String assigneeName) { this.assigneeName = assigneeName; }
        public String getBusinessKey() { return businessKey; }
        public void setBusinessKey(String businessKey) { this.businessKey = businessKey; }
        public String getBusinessType() { return businessType; }
        public void setBusinessType(String businessType) { this.businessType = businessType; }
        public Map<String, Object> getBusinessData() { return businessData; }
        public void setBusinessData(Map<String, Object> businessData) { this.businessData = businessData; }
        public String getProcessInstanceId() { return processInstanceId; }
        public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; }
        public String getProcessDefinitionId() { return processDefinitionId; }
        public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; }
        public String getProcessDefinitionKey() { return processDefinitionKey; }
        public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; }
        public String getProcessTaskId() { return processTaskId; }
        public void setProcessTaskId(String processTaskId) { this.processTaskId = processTaskId; }
        public String getFormId() { return formId; }
        public void setFormId(String formId) { this.formId = formId; }
        public String getFormDataId() { return formDataId; }
        public void setFormDataId(String formDataId) { this.formDataId = formDataId; }
        public LocalDateTime getStartTime() { return startTime; }
        public void setStartTime(LocalDateTime startTime) { this.startTime = startTime; }
        public LocalDateTime getDueTime() { return dueTime; }
        public void setDueTime(LocalDateTime dueTime) { this.dueTime = dueTime; }
        public List<String> getTags() { return tags; }
        public void setTags(List<String> tags) { this.tags = tags; }
        public String getRemark() { return remark; }
        public void setRemark(String remark) { this.remark = remark; }
        public Map<String, Object> getExtend() { return extend; }
        public void setExtend(Map<String, Object> extend) { this.extend = extend; }
    }
    
    public static class TaskUpdateRequest {
        private String title;
        private String description;
        private String type;
        private String category;
        private Integer priority;
        private String assigneeId;
        private String assigneeName;
        private Map<String, Object> businessData;
        private LocalDateTime dueTime;
        private List<String> tags;
        private String remark;
        private Map<String, Object> extend;
        
        // Getters and Setters
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        public String getType() { return type; }
        public void setType(String type) { this.type = type; }
        public String getCategory() { return category; }
        public void setCategory(String category) { this.category = category; }
        public Integer getPriority() { return priority; }
        public void setPriority(Integer priority) { this.priority = priority; }
        public String getAssigneeId() { return assigneeId; }
        public void setAssigneeId(String assigneeId) { this.assigneeId = assigneeId; }
        public String getAssigneeName() { return assigneeName; }
        public void setAssigneeName(String assigneeName) { this.assigneeName = assigneeName; }
        public Map<String, Object> getBusinessData() { return businessData; }
        public void setBusinessData(Map<String, Object> businessData) { this.businessData = businessData; }
        public LocalDateTime getDueTime() { return dueTime; }
        public void setDueTime(LocalDateTime dueTime) { this.dueTime = dueTime; }
        public List<String> getTags() { return tags; }
        public void setTags(List<String> tags) { this.tags = tags; }
        public String getRemark() { return remark; }
        public void setRemark(String remark) { this.remark = remark; }
        public Map<String, Object> getExtend() { return extend; }
        public void setExtend(Map<String, Object> extend) { this.extend = extend; }
    }
    
    public static class TaskAssignRequest {
        private String assigneeId;
        private String assigneeName;
        
        public String getAssigneeId() { return assigneeId; }
        public void setAssigneeId(String assigneeId) { this.assigneeId = assigneeId; }
        public String getAssigneeName() { return assigneeName; }
        public void setAssigneeName(String assigneeName) { this.assigneeName = assigneeName; }
    }
    
    public static class TaskBatchAssignRequest {
        private List<String> ids;
        private String assigneeId;
        private String assigneeName;
        
        public List<String> getIds() { return ids; }
        public void setIds(List<String> ids) { this.ids = ids; }
        public String getAssigneeId() { return assigneeId; }
        public void setAssigneeId(String assigneeId) { this.assigneeId = assigneeId; }
        public String getAssigneeName() { return assigneeName; }
        public void setAssigneeName(String assigneeName) { this.assigneeName = assigneeName; }
    }
    
    public static class TaskStatusUpdateRequest {
        private String status;
        
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
    }
    
    public static class TaskBatchStatusUpdateRequest {
        private List<String> ids;
        private String status;
        
        public List<String> getIds() { return ids; }
        public void setIds(List<String> ids) { this.ids = ids; }
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
    }
    
    public static class TaskPriorityUpdateRequest {
        private Integer priority;
        
        public Integer getPriority() { return priority; }
        public void setPriority(Integer priority) { this.priority = priority; }
    }
    
    public static class TaskBatchPriorityUpdateRequest {
        private List<String> ids;
        private Integer priority;
        
        public List<String> getIds() { return ids; }
        public void setIds(List<String> ids) { this.ids = ids; }
        public Integer getPriority() { return priority; }
        public void setPriority(Integer priority) { this.priority = priority; }
    }
    
    public static class TaskDueTimeUpdateRequest {
        private LocalDateTime dueTime;
        
        public LocalDateTime getDueTime() { return dueTime; }
        public void setDueTime(LocalDateTime dueTime) { this.dueTime = dueTime; }
    }
    
    public static class TaskBatchDueTimeUpdateRequest {
        private List<String> ids;
        private LocalDateTime dueTime;
        
        public List<String> getIds() { return ids; }
        public void setIds(List<String> ids) { this.ids = ids; }
        public LocalDateTime getDueTime() { return dueTime; }
        public void setDueTime(LocalDateTime dueTime) { this.dueTime = dueTime; }
    }
    
    public static class TaskTagsUpdateRequest {
        private List<String> tags;
        
        public List<String> getTags() { return tags; }
        public void setTags(List<String> tags) { this.tags = tags; }
    }
    
    public static class TaskBatchTagsUpdateRequest {
        private List<String> ids;
        private List<String> tags;
        
        public List<String> getIds() { return ids; }
        public void setIds(List<String> ids) { this.ids = ids; }
        public List<String> getTags() { return tags; }
        public void setTags(List<String> tags) { this.tags = tags; }
    }
    
    public static class TaskApprovalRequest {
        private String comment;
        private Map<String, Object> variables;
        
        public String getComment() { return comment; }
        public void setComment(String comment) { this.comment = comment; }
        public Map<String, Object> getVariables() { return variables; }
        public void setVariables(Map<String, Object> variables) { this.variables = variables; }
    }
    
    public static class TaskRejectRequest {
        private String reason;
        private Map<String, Object> variables;
        
        public String getReason() { return reason; }
        public void setReason(String reason) { this.reason = reason; }
        public Map<String, Object> getVariables() { return variables; }
        public void setVariables(Map<String, Object> variables) { this.variables = variables; }
    }
    
    public static class TaskTransferRequest {
        private String targetUserId;
        private String targetUserName;
        private String reason;
        
        public String getTargetUserId() { return targetUserId; }
        public void setTargetUserId(String targetUserId) { this.targetUserId = targetUserId; }
        public String getTargetUserName() { return targetUserName; }
        public void setTargetUserName(String targetUserName) { this.targetUserName = targetUserName; }
        public String getReason() { return reason; }
        public void setReason(String reason) { this.reason = reason; }
    }
}